# 上线文件
# 开发配置文件

# 首页轮播图个数
import datetime

BANNER_COUNTER = 3

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 把BASE_DIR加入到环境变量
import sys

# print(sys.path)
# print(BASE_DIR)
sys.path.insert(1, BASE_DIR)
# 把apps的路径加入到环境变量
sys.path.insert(1, os.path.join(BASE_DIR, 'apps'))
# print(sys.path)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'a)b7#=c0zc*x==4ya$#8a8gg3by_=si9q#afmi@io!!yb=m35s'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

# 运行的host，服务端的地址，买的服务器的公网ip

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'user.apps.UserConfig',  # 因为apps目录已经添加到环境变量里了， 所以查找app从环境变量里查找，且可以不加路径
    'home.apps.HomeConfig',
    'xadmin',
    'crispy_forms',
    'reversion',
    'corsheaders',
    'course',
    'order.apps.OrderConfig',
    'django_filters',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 处理跨域
    # 'AKapi.utils.middle.MyMiddle',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

ROOT_URLCONF = 'AKapi.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'AKapi.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'AKapi',
        'USER': 'root',
        'PASSWORD': 'FW249746',
        'HOST': '127.0.0.1',
        'PORT': 3306

    },

}
import pymysql

pymysql.install_as_MySQLdb()

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

# from user import models  # 导入没问题，因为已经把apps路径添加到环境变量里了，但是pycharm会飘红

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# AUTH_USER_MODEL = 'user.User'
AUTH_USER_MODEL = 'user.user'  # 两种写法都行

REST_FRAMEWORK = {
    # 'EXCEPTION_HANDLER': 'AKapi.utils.exceptions.common_exception_handler',
    'DEFAULT_THROTTLE_RATES': {
        'sms': '1/m'
    },

}

# 真实项目上线后，日志文件打印级别不能过低，因为一次日志记录就是一次文件io操作
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
        },
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            # 实际开发建议使用WARNING
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {
            # 实际开发建议使用ERROR
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            # 日志位置,日志文件名,日志保存目录必须手动创建，注：这里的文件路径要注意BASE_DIR代表的是小luffyapi
            'filename': os.path.join(os.path.dirname(BASE_DIR), "logs", "luffy.log"),
            # 日志文件的最大值,这里我们设置300M
            'maxBytes': 300 * 1024 * 1024,
            # 日志文件的数量,设置最大日志数量为10
            'backupCount': 10,
            # 日志格式:详细格式
            'formatter': 'verbose',
            # 文件内容编码
            'encoding': 'utf-8'
        },
    },
    # 日志对象
    'loggers': {
        'django': {
            'handlers': ['console', 'file'],
            'propagate': True,  # 是否让日志信息继续冒泡给其他的日志处理系统
        },
    }
}

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'authorization',
    'content-type',
)

# 配置jwt的过期时间
JWT_AUTH = {
    # 过期时间7天
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
    # 自定义认证结果，见下方序列化user和自定义response
    # 如果不自定义，返回的格式是固定的，只有token字段
    # 'JWT_RESPONSE_PAYLOAD_HANDLER': ''
}

# 1.将缓存存储位置配置到redis中：settings.py
# django默认不支持redis缓存
# from django.core.cache.backends.filebased import FileBasedCache
# from django_redis.cache import RedisCache
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",  # 以后所有的cache都缓存到了redis中
        "LOCATION": "redis://127.0.0.1:6379",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
            "DECODE_RESPONSES": True,
            "PASSWORD": "",
        }
    }
}

# # 2.操作cache模块直接操作缓存：views.py
# from django.core.cache import cache  # 结合配置文件实现插拔式
# # 存放token，可以直接设置过期时间
# cache.set('token', 'header.payload.signature', 300)
# # 取出token
# token = cache.get('token')


# 支付完后两个回调地址
# 上线后必须换成公网地址
# 后台基URL
BASE_URL = 'http://121.196.175.94:8000'
# 前台基URL
LUFFY_URL = 'http://121.196.175.94'
# 支付宝同步异步回调接口配置
# 后台异步回调接口
NOTIFY_URL = BASE_URL + "/order/success/"
# 前台同步回调接口，没有 / 结尾
RETURN_URL = LUFFY_URL + "/pay/success"